﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using HslCommunication;
using HslCommunication.Profinet.Siemens;

namespace Net_SCADA
{
    public class hsl_Server
    {
        public SiemensS7Net SiemensPLC { get; }
        public bool isPlCConnected { get; set; } = false;
        public hsl_Server(string ip)
        {
            if (IsIP(ip))
                SiemensPLC = new SiemensS7Net(SiemensPLCS.S1500, ip);
            else
                MessageBox.Show("[{0}]不是一个正确的IP地址,请确认相关并修改设置项后重新启动软件！",ip);
        }

        public bool ConnectToPLC()
        {
            if (SiemensPLC != null)
            {
                OperateResult res = SiemensPLC.ConnectServer();
                return isPlCConnected = res.IsSuccess;
            }else
            {
                return isPlCConnected = false;
            }
        }

        public bool DisconnectFromPLC()
        {
            if (isPlCConnected)
            {
                isPlCConnected = false;
                OperateResult res = SiemensPLC.ConnectClose();
                return res.IsSuccess;
            }
            return true;
        }

        public bool TestPLC()
        {
            if (isPlCConnected)
            {
                OperateResult<bool> res = SiemensPLC.ReadBool("M0.0");
                return res.IsSuccess;
            }
            return false;
        }

        public static bool IsIP(string ip)
        {
            //如果为空，认为验证合格
            if (string.IsNullOrEmpty(ip))
            {
                return true;
            }
            //清除要验证字符串中的空格
            ip = ip.Trim();
            //模式字符串
            string pattern = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
            //验证
            return Regex.IsMatch(ip, pattern);
        }
    }
}
